package org.example.ui;

import org.example.Server;

import javax.swing.*;
import java.awt.*;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.*;

public class ServerUI extends JFrame {

    private JTextArea logArea;
    private JButton startButton;
    private JButton stopButton;
    private JTextField portField;

    private ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
    private Future<?> serverFuture;
    private AsynchronousServerSocketChannel serverChannel;

    public ServerUI() {
        setTitle("War3 Server");
        setSize(600, 450);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 输入端口
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        inputPanel.add(new JLabel("监听端口:"));
        portField = new JTextField("8888", 6);
        inputPanel.add(portField);

        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);

        // 按钮
        startButton = new JButton("启动服务器");
        stopButton = new JButton("停止服务器");
        stopButton.setEnabled(false);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);

        // 布局
        setLayout(new BorderLayout());
        add(inputPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 事件绑定
        startButton.addActionListener(e -> startServer());
        stopButton.addActionListener(e -> stopServer());
    }

    private void startServer() {
        try {
            int port = Integer.parseInt(portField.getText().trim());

            serverFuture = executor.submit(() -> {
                try {
                    serverChannel = AsynchronousServerSocketChannel.open();
                    serverChannel.bind(new InetSocketAddress("0.0.0.0", port));
                    log("服务器已启动，监听端口 " + port);

                    while (!Thread.interrupted() && serverChannel.isOpen()) {
                        var asc = serverChannel.accept().get();
                        log("有新客户端接入: " + asc.getRemoteAddress());
                        Server.handleClient(asc);
                    }

                } catch (Exception ex) {
                    log("服务器异常: " + ex.getMessage());
                }
            });

            startButton.setEnabled(false);
            stopButton.setEnabled(true);

        } catch (Exception ex) {
            log("启动失败: " + ex.getMessage());
        }
    }

    private void stopServer() {
        try {
            if (serverFuture != null) {
                serverFuture.cancel(true);
            }
            if (serverChannel != null && serverChannel.isOpen()) {
                serverChannel.close();
            }
            log("服务器已停止");

            startButton.setEnabled(true);
            stopButton.setEnabled(false);

        } catch (Exception ex) {
            log("停止失败: " + ex.getMessage());
        }
    }

    private void log(String message) {
        SwingUtilities.invokeLater(() -> {
            logArea.append(message + "\n");
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ServerUI ui = new ServerUI();
            ui.setVisible(true);
        });
    }
}
